const Movie = require('../models/movie')
const _ = require('underscore')

  // 详情页

exports.detail = (req, res) => {
  let id = req.params.id
  Movie.findById(id, (err, movie) => {
    if (err) return console.log(err)
    res.render('detail', {
      title: 'movie ' + movie.title,
      movie: movie
    })
  })
}

exports.new = (req, res) => {
  res.render('admin', {
    title: 'movie 后台录入页',
    movie: {
      title: '',
      doctor: '',
      country: '',
      year: '',
      poster: '',
      flash: '',
      summary: '',
      language: ''
    }
  })
}

exports.update = (req, res) => {
  let id = req.params.id
  if (id) {
    Movie.findById(id, (err, movie) => {
      res.render('admin', {
        title: 'movie 后台更新页 ',
        movie: movie
      })
    })
  }
}

exports.save = (req, res) => {
  let id = req.body.movie._id
  let movieObj = req.body.movie
  let _movie = null
  if (id !== 'undefined') {
    Movie.findById(id, function (err, movie) {
      if (err) return console.log(err)

      _movie = _.extend(movie, movieObj)
      _movie.save(function (err, movie) {
        if (err) return console.log(err)
        res.redirect('/movie/' + movie._id)
      })
    })
  } else {
    _movie = new Movie({
      doctor: movieObj.doctor,
      title: movieObj.title,
      country: movieObj.country,
      language: movieObj.language,
      year: movieObj.year,
      poster: movieObj.poster,
      summary: movieObj.summary,
      flash: movieObj.flash
    })
    _movie.save(function (err, movie) {
      if (err) return console.log(err)


      res.redirect('/movie/' + movie._id)
    })
  }
}

exports.list = (req, res) => {
  Movie.fetch((err, movies) => {
    if (err) return console.log(err)
    res.render('list', {
      title: 'movie 列表页',
      movies: movies
    })
  })
}

exports.del = (req, res) => {
  let id = req.query.id
  if (id) {
    Movie.remove({ _id: id }, (err, movie) => {
      if (err) return console.log(err)
      res.json({
        success: 1
      })
    })
  }
}